<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告文字区域 -->
      <el-alert
        title="注意:只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>

      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <!-- 选择商品分类的级联选择框 -->
          <span>选择商品分类:</span>
          <el-cascader
            v-model="selectedCateKeys"
            :options="cateList"
            :props="{
              expandTrigger: 'hover',
              value: 'cat_id',
              label: 'cat_name',
              children: 'children',
            }"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数的按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
          >
            添加参数
          </el-button>
          <!-- 动态参数的表格 -->
          <el-table :data="manyTableData" border stripe style="width: 50%">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template #default="{ row }">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  v-for="(item, index) in row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入的文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="row.inputVisible"
                  v-model="row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(row)"
                  @blur="handleInputConfirm(row)"
                >
                </el-input>
                <!-- 添加的按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(row.attr_id)"
                  >编辑</el-button
                ><el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加静态属性的按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
          >
            添加属性
          </el-button>
          <!-- 静态属性的表格 -->
          <el-table :data="onlyTableData" border stripe style="width: 50%">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template #default="{ row }">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  v-for="(item, index) in row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入的文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="row.inputVisible"
                  v-model="row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(row)"
                  @blur="handleInputConfirm(row)"
                >
                </el-input>
                <!-- 添加的按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"> </el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(row.attr_id)"
                  >编辑</el-button
                ><el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数的对话框 -->
    <el-dialog
      :title="this.activeName === 'many' ? '添加动态参数' : '添加静态属性'"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 添加参数的对话框 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item
          :label="this.activeName === 'many' ? '添加动态参数' : '添加静态属性'"
          prop="attr_name"
          label-width="150px"
        >
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑参数的对话框 -->
    <el-dialog
      :title="this.activeName === 'many' ? '编辑动态参数' : '编辑静态属性'"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 编辑参数的对话框 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item
          :label="this.activeName === 'many' ? '编辑动态参数' : '编辑静态属性'"
          prop="attr_name"
          label-width="150px"
        >
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getCateListApi } from '../../api/cate'
import { getParamsApi, addParamsApi, getParamsByIdApi, editParamsApi, removeParamsApi, submitTagApi } from '../../api/params'
export default {
  data () {
    return {
      // 分类的数据
      cateList: [],
      // 级联选择框双向绑定的数据
      selectedCateKeys: [],
      // 被激活的页签的名称
      activeName: 'many',
      // 动态参数的数据
      manyTableData: [],
      // 静态参数的数据
      onlyTableData: [],
      // 控制添加参数对话框的显示与隐藏
      addDialogVisible: false,
      // 添加参数的表单数据对象
      addForm: {
        attr_name: ''
      },
      // 添加参数的表单数据校验规则
      addFormRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      },
      // 控制编辑参数对话框的显示与隐藏
      editDialogVisible: false,
      // 编辑参数的表单数据对象
      editForm: {},
      // 编辑参数的表单数据校验规则
      editFormRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 获取所有商品分类
    async getCateList () {
      const { data } = await getCateListApi({ type: 3 })
      console.log(data)
      if (data.meta.status !== 200) return false
      this.cateList = data.data
    },
    // 级联选择框选中项发生变化,触发的函数
    handleChange () {
      // console.log(this.selectedCateKeys)
      this.getParamsData()
    },
    // tab页签点击事件的处理函数
    handleTabClick () {
      console.log(this.activeName)
      this.getParamsData()
    },
    // 因为点击切换页签和选择级联选择框的选中项,都要触发这个函数,所以抽离出来封装
    // 获取参数的列表数据
    async getParamsData () {
      // 说明选中的不是三级分类
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      // 说明选中的是三级分类
      // 根据所选分类的Id,和所处的面板,获取对应的参数发起请求
      const { data } = await getParamsApi(this.cat_id, this.activeName)
      console.log(data)
      if (data.meta.status !== 200) return this.$message.error('获取商品参数失败!')
      this.$message.success('获取商品参数成功!')
      // 为渲染参数的展开行的描述做数据结构的准备
      data.data.forEach(item => {
        // 解决没有参数项时,空字符串split后会生成一个含有空字符串的数组
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制文本框的显示与隐藏
        item.inputVisible = false
        // 文本框中输入的值
        item.inputValue = ''
      })
      console.log(data.data)
      // 获取到的数据有的是给动态参数页签使用,有的给静态属性页签使用,所以不能直接赋值,而是要先做出判断
      if (this.activeName === 'many') {
        this.manyTableData = data.data
      } else {
        this.onlyTableData = data.data
      }
    },
    // 监听添加参数对话框的关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮,添加参数
    addParams () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data } = await addParamsApi(this.cat_id, this.addForm.attr_name, this.activeName)
        // console.log(data)
        if (data.meta.status !== 201) return this.$message.error('添加失败！')
        this.$message.success('添加成功')
        this.addDialogVisible = false
        this.getParamsData()
      })
    },
    // 点击按钮显示编辑对话框
    async showEditDialog (attr_id) {
      try {
        const { data } = await getParamsByIdApi(this.cat_id, attr_id, this.activeName)
        console.log(data)
        this.editForm = data.data
        this.editDialogVisible = true
      } catch (error) {
        console.log(error)
        this.$message.error('获取参数信息失败!')
      }
    },
    // 监听编辑参数对话框的关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 点击按钮编辑参数
    editParams () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return false
        const { data } = await editParamsApi(this.cat_id, this.editForm.attr_id, this.editForm.attr_name, this.activeName)
        // console.log(data)
        if (data.meta.status !== 200) return this.$message.error('编辑参数失败!')
        this.$message.success({
          content: '编辑参数成功!',
          duration: 1.5
        })
        this.getParamsData()
        this.editDialogVisible = false
      })
    },
    // 根据Id删除参数
    removeParams (attr_id) {
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data } = await removeParamsApi(this.cat_id, attr_id)
        console.log(data)
        if (data.meta.status !== 200) {
          return this.$message.error('删除失败!')
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getParamsData()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 文本框失去焦点或按下enter都会触发
    async handleInputConfirm (row) {
      // console.log('ok')
      // 输入不合法
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return false
      }
      // 输入合法
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 发起请求,保存新tag
      this.saveAttr_vals(row)
    },
    // 将对attr_vals的操作保存到数据库中
    async saveAttr_vals (row) {
      // 发起请求,保存新tag
      const { data } = await submitTagApi(this.cat_id, row.attr_id, row.attr_name, this.activeName, row.attr_vals.join(' '))
      // console.log(data)
      if (data.meta.status !== 200) {
        return this.$message.error('更新参数项失败')
      }
      this.$message.success('更新参数项成功')
    },
    // 点击按钮展示文本输入框
    showInput (row) {
      row.inputVisible = true
      // 文本框自动获取焦点
      // $nextTick 就是当页面的元素被渲染之后才会执行回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除tag(参数可选项)
    handleClose (index, row) {
      row.attr_vals.splice(index, 1)
      this.saveAttr_vals(row)
    }
  },
  created () {
    this.getCateList()
  },
  computed: {
    // 如果按钮需要被禁用,返回true,否则返回false
    isBtnDisabled () {
      if (this.selectedCateKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    // 被选中的三级分类的id
    cat_id () {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 6px;
}
.input-new-tag {
  margin: 6px;
  width: 120px;
}
.button-new-tag {
  margin: 6px;
}
</style>
